import { createDraw } from '../../../../../utils/createDraw'
import * as turf from '@turf/turf'

export const measureArea = ($map) => {

    const source = new ol.source.Vector({})
    const layer = new ol.layer.Vector({
        source,
        title:"面积画笔"
    })
    $map.addLayer(layer)

    const draw = createDraw({
        type: "Polygon",
        source
    })
    $map.addInteraction(draw)

    draw.on('drawend', (evt) => {
        const position = evt.feature.getGeometry().getCoordinates()
        var polygon = turf.polygon(position);
        var area = (turf.area(polygon) / 1000000).toFixed(2);

        //计算中心点
        var polygon = turf.polygon(position);
        var center = turf.centroid(polygon);

        //添加标注
        const markerSource = new ol.source.Vector({
            features: new ol.format.GeoJSON().readFeatures({
                type: "FeatureCollection",
                features: [center]
            })
        })
        const markerLayer = new ol.layer.Vector({
            source: markerSource,
            style: new ol.style.Style({
                text: new ol.style.Text({
                    offsetX: 0,
                    offsetY: 10,
                    font: 'normal 14px 微软雅黑',
                    text: `${area} 平方千米`,
                    fill: new ol.style.Fill({ color: '#333' }),
                    stroke: new ol.style.Stroke({ color: "#0000ff", width: 2 })
                })
            }),
            title:"面积标注"
        })
        $map.addLayer(markerLayer)
    })

    return { draw }
}